#include "TerminalStateGrid.h"
#include "app.h"

DEFINE_EVENT_TYPE(wxEVT_COMMAND_TERM_STATE_CHANGE)

IMPLEMENT_DYNAMIC_CLASS(wxTermStateChangeEvent, wxNotifyEvent)

BEGIN_EVENT_TABLE(TerminalStateGrid, wxGrid)
    EVT_GRID_CELL_RIGHT_CLICK(TerminalStateGrid::OnRightUp)
    EVT_GRID_CELL_LEFT_CLICK(TerminalStateGrid::OnLeftUp)
    EVT_TERM_STATE_CHANGE(TerminalStateGrid::OnTermStateChange)
END_EVENT_TABLE()

void TerminalStateGrid::OnTermStateChange(wxTermStateChangeEvent& event)
{
  if ((event.GetR()<GetNumberRows()) && (event.GetC()<GetNumberCols())){
    BeginBatch();
    SetCellTextColour(event.GetR(),event.GetC(),event.GetCol());
    EndBatch();
  }
}

void TerminalStateGrid::OnLeftUp(wxGridEvent& event){	
	
	SelectBlock(event.GetRow(), event.GetCol(),event.GetRow(), event.GetCol(),event.ControlDown());
}

void TerminalStateGrid::OnRightUp(wxGridEvent& event){
	wxPoint pos=event.GetPosition();

    wxMenu menu(_T(""));
    menu.Append(CMENU_START_TRACE, _("Start Trace"));

    PopupMenu(&menu, pos.x, pos.y);
	
}
TerminalStateGrid::TerminalStateGrid(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, const long style)
	:wxGrid(parent,id,pos,size,style){
	BeginBatch();
	CreateGrid( 1, DEFAULT_TERM_STATE_GRID_COLS_NUM);
	SetRowLabelSize(0);
	DisableCellEditControl();
	SetDefaultColSize(30);
	SetDefaultRowSize(30);
	DisableDragColSize();
	DisableDragRowSize();
	SetDefaultCellAlignment(wxALIGN_CENTRE,wxALIGN_CENTRE);
	SetColLabelAlignment(wxALIGN_CENTRE,wxALIGN_CENTRE);
	SetColLabelSize(20);
	TermLength=-1;
	InitTerms(DEFAULT_TERM_NUM);
	EndBatch();
}

TerminalStateGrid::~TerminalStateGrid(){
}

/**
 * @brief 初始化终端用户界面
 *
 * 只是在界面上初始化终端
 * 
 */
void TerminalStateGrid::InitTerms(int TermNum){
	BeginBatch();
	//int ColsNum=DEFAULT_TERM_STATE_GRID_COLS_NUM;
	int ColsNum=GetClientSize().x/30;
	if (ColsNum<10) ColsNum=10;
	int RowsNum=TermNum/ColsNum;
	if (TermLength != TermNum){
	    if ((RowsNum *ColsNum)<TermNum) RowsNum+=1;
	    if (GetNumberCols()>0){
		DeleteCols(0,GetNumberCols());
	    }
	    if (GetNumberRows()>0){
		DeleteRows(0,GetNumberRows());
	    }
	    AppendCols(ColsNum);
	    AppendRows(RowsNum);
	}
	for (int i=0;i<TermNum;i++){
	    int r = i / ColsNum;
	    int c = i % ColsNum;
	    if (TermLength != TermNum){
		SetCellValue(r,c,wxString::Format(wxT("%d"),i));	
		SetReadOnly(r,c);
	    }
	    SetCellTextColour(r,c,*wxBLACK);
	}
	TermLength = TermNum;
	EndBatch();
	
}

